//
//  SearchViewController.m
//  project
//
//  Created by lanou on 15/11/3.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "SearchViewController.h"
#import "PKRequestManager.h"
#import "SearchViewCell.h"
#import "CatogryArtifactViewController.h"
#import "HotListCell.h"
#import "ListModel.h"
#import "OtherTableViewModel.h"
#import "OtherTableViewCell.h"
#import "MJRefresh.h"
#import "HotDetailViewController.h"
#import "StrategyDetailsViewController.h"

@interface SearchViewController ()<UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UICollectionView *listCollectionView;
@property (nonatomic, strong)NSMutableArray *listArray;
@property (nonatomic, strong)UIView *listView;
@property (nonatomic, strong)NSString *requestStr;
@property (nonatomic, strong)UISegmentedControl *segmentControl;
@property (nonatomic, strong)UIView *view1;
@property (nonatomic, strong)UIView *view2;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *tableViewArray;
@property (nonatomic, strong)NSString *str;
@property (nonatomic, strong)UILabel *label3;


@end

@implementation SearchViewController

int offset = 0;
-(void)viewWillDisappear:(BOOL)animated
{
    [_searchBar resignFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(30, 10, kWidth-50 , 20)];
    _searchBar.placeholder = @"选份礼物给最爱的人";
   
    _searchBar.delegate = self;

   self.navigationItem.titleView = _searchBar;
   // [self.navigationController.navigationBar addSubview:_searchBar];
    _dataArray = [NSMutableArray array];
    [self layoutView];
    [self searchGift];
    [self requestData];
    
    [self.view bringSubviewToFront:_scrollView];
     [_searchBar becomeFirstResponder];
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    _str =_searchBar.text;
    [self.view bringSubviewToFront:_listView];
    _requestStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?keyword=%@&limit=20&offset=0&sort=",[_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"%@", _requestStr);

    [_listView bringSubviewToFront:_collectionView];
    [self requstGiftData];
    if (self.listArray.count == 0)
    {
        _label3.hidden = NO;
    }
    else
    {
        _label3.hidden = YES;
    }
    [_searchBar resignFirstResponder];
    
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (_searchBar.text != nil)
    {
        [self.view bringSubviewToFront:_scrollView];
        [_searchBar becomeFirstResponder];
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar;
{
    _searchBar.frame = CGRectMake(0, 10, kWidth - 60, 20);
    _searchBar.showsCancelButton = YES;
    for(id cc in [searchBar.subviews[0] subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    
}



- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    _searchBar.showsCancelButton = NO;
   
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
  
    NSArray *array = [self.view subviews];
    if (_listView == [array lastObject]) {
        [_searchBar resignFirstResponder];
        return;
    }
    [_searchBar resignFirstResponder];
        [self.navigationController popToRootViewControllerAnimated:YES];
    
}

-(void)layoutView
{

    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 70, kWidth, kHeight - 40)];
    [self.view addSubview:_scrollView];
    _scrollView.contentSize = CGSizeMake(kWidth, kHeight +1);
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, 100, 20)];
    label.textColor = [UIColor grayColor];
    label.text = @"大家都在搜";
    label.font = [UIFont systemFontOfSize:12];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:label];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);


    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 60, kWidth, 200) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerClass:[SearchViewCell class] forCellWithReuseIdentifier:@"cell"];
 
    [_scrollView addSubview:_collectionView];
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 290, kWidth, 40)];
    view.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:view];
    
    UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"iconfont-dingweizhuanhuan"]];
    imgView.backgroundColor = [UIColor greenColor];
    imgView.frame = CGRectMake(10, 10, 20, 20);
    imgView.layer.masksToBounds = YES;
    imgView.layer.cornerRadius = 10;
    [view addSubview:imgView];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(40, 10, 200, 20)];
    label1.font = [UIFont systemFontOfSize:13];
   label1.text = @"使用选礼神器快速挑选礼物";
    label1.textColor = [UIColor grayColor];
    [view addSubview:label1];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gift)];
    [view addGestureRecognizer:singleTap];
    

    
}


-(void)gift
{
    [_searchBar endEditing:YES];
    CatogryArtifactViewController  *giftVC = [[CatogryArtifactViewController alloc]init];
    [self.navigationController pushViewController:giftVC animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == _listCollectionView)
    {
        return self.listArray.count;
    }
    else
    {
    return self.dataArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _listCollectionView)
    {
        HotListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"listCell" forIndexPath:indexPath];
       [cell ConfigModel:self.listArray[indexPath.item]];
        return cell;
    }
    else
    {
    SearchViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.titleLabel.text = _dataArray[indexPath.item];
    cell.layer.borderWidth = 1;
    [cell.layer setBorderColor:[[[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1] CGColor]];
    return cell;
    }
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _listCollectionView)
    {
         return CGSizeMake((kWidth - 30)/2, (kWidth - 30)/2 + 80);

    }
   else
   {
       
       CGFloat width = [SearchViewCell widthForString:_dataArray[indexPath.item]];
       
       CGSize size = CGSizeMake(width, 30);
       return size;
      
   }
}

-(void)requestData
{
    [PKRequestManager requestWithTypeP:GET urlString:@"http://api.liwushuo.com/v2/search/hot_words" parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic = dict[@"data"];
        NSArray *array = dic[@"hot_words"];
        for (NSString *str in array)
        {
            [_dataArray addObject:str];
        }
        [self.collectionView reloadData];
        
        
    } error:^(NSError *error) {
        
    }];

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _collectionView)
    {
        [_searchBar resignFirstResponder];
        _searchBar.text = self.dataArray[indexPath.item];
        [self.view bringSubviewToFront:_listView];
      
        _str = self.dataArray[indexPath.item];
        
        
        _requestStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?keyword=%@&offset=0&sort=", [_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        [self requstGiftData];
    }
    
    else
    {
        ListModel *model  =  self.listArray[indexPath.item];
        HotDetailViewController *giftDetail = [[HotDetailViewController alloc]init];

       model.url =  [NSString stringWithFormat:@"http://www.liwushuo.com/items/%@", model.idd];
//        detailModel.data.id = [NSString stringWithFormat:@"%@", model.id];
        giftDetail.model = model;
        [self.navigationController pushViewController:giftDetail animated:YES];
    }

    
   // http://api.liwushuo.com/v2/search/item?keyword=%E6%89%8B%E6%9C%BA%E5%A3%B3&limit=20&offset=0&sort=
}

-(void)searchGift
{
    [_searchBar resignFirstResponder];
    _listView = [[UIView alloc]initWithFrame:self.view.bounds];
    _listView.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.view addSubview:_listView];
    
    _segmentControl = [[UISegmentedControl alloc]initWithItems:@[@"礼物", @"攻略"]];
    _segmentControl.backgroundColor = [UIColor whiteColor];
    _segmentControl.layer.borderWidth = 0.5;
    _segmentControl.layer.borderColor = [[[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1] CGColor];
 _segmentControl.tintColor = [UIColor whiteColor];
       NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName: [UIColor grayColor]};
    [_segmentControl setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];
    
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName: [UIColor grayColor]};
    [_segmentControl setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    _segmentControl.frame = CGRectMake(0, 65, kWidth, 30);
    [_listView addSubview:_segmentControl];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(kWidth/2, 70, 1, 20)];
    view.backgroundColor = [[UIColor alloc] initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [_segmentControl addSubview:view];
    
    _view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 95, kWidth/2, 2)];
    _view1.backgroundColor = [[UIColor alloc]initWithRed:221/255.0 green:160/255.0 blue:221/255.0 alpha:1];
    [_listView addSubview:_view1];
    
    _view2 = [[UIView alloc]initWithFrame:CGRectMake(kWidth/2, 95, kWidth/2, 2)];
    _view2.backgroundColor = [UIColor whiteColor];
    [_listView addSubview:_view2];
    
    [_segmentControl addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
    
    [self addTableViewAndColecion];
    
    _label3 = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, kWidth, 30)];
    _label3.text =@"没有搜索到相关结果";
    _label3.textColor = [UIColor grayColor];
    _label3.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_label3];
    _label3.hidden = YES;
        _listArray = [NSMutableArray array];
    _tableViewArray = [NSMutableArray array];
    
    [self requstGiftData];

}

-(void)addTableViewAndColecion
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    CGFloat item = (kWidth - 30)/2;
    layout.itemSize = CGSizeMake(item, item + 80);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    _listCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 100, kWidth, kHeight - 50) collectionViewLayout:layout];
    _listCollectionView.dataSource = self;
    _listCollectionView.delegate = self;
    _listCollectionView.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [_listCollectionView registerClass:[HotListCell class] forCellWithReuseIdentifier:@"listCell"];
    
    _listCollectionView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self requestMoreData];
    }];
    [_listView  addSubview:_listCollectionView];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, kWidth, kHeight - 50)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView registerClass:[OtherTableViewCell class] forCellReuseIdentifier:@"tableView"];
    _tableView.rowHeight = 200;
    [self.listView addSubview:_tableView];
    
    [_listView bringSubviewToFront:_listCollectionView];
    

}

-(void)change:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0)
    {
        _view1.backgroundColor = [[UIColor alloc]initWithRed:221/255.0 green:160/255.0 blue:221/255.0 alpha:1];
        _view2.backgroundColor = [UIColor whiteColor];
        _requestStr = [_requestStr stringByReplacingOccurrencesOfString:@"post" withString:@"item"];
        [_listView bringSubviewToFront:_listCollectionView];
        [self requstGiftData];
    }
    else
    {
      _view2.backgroundColor =  [[UIColor alloc]initWithRed:221/255.0 green:160/255.0 blue:221/255.0 alpha:1];
        _view1.backgroundColor = [UIColor whiteColor];
        _requestStr = [_requestStr stringByReplacingOccurrencesOfString:@"item" withString:@"post"];
        [_listView bringSubviewToFront:_tableView];
        [self requestTableViewData];
    }
}

-(void)requstGiftData
{
    [PKRequestManager requestWithTypeP:GET urlString:_requestStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dic = dict[@"data"];
        NSArray *array = dic[@"items"];
        [_listArray removeAllObjects];
        for (NSDictionary *dic in array)
        {
            ListModel *model = [[ListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.listArray addObject:model];
        }
        [_listCollectionView reloadData];
        
    } error:^(NSError *error) {
        
    }];
}

-(void)requestTableViewData
{
    [PKRequestManager requestWithTypeP:GET urlString:_requestStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dic = dict[@"data"];
        NSArray *array = dic[@"posts"];
        [_tableViewArray removeAllObjects];
        for (NSDictionary *dic in array)
        {
            OtherTableViewModel *model = [[OtherTableViewModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.tableViewArray addObject:model];
        }
        [_tableView reloadData];
        
    } error:^(NSError *error) {
        
    }];
    
}

-(void)requestMoreData
{
    offset = offset +20;
   _requestStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?keyword=%@&offset=%d&sort=", [_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], offset];
    [PKRequestManager requestWithTypeP:GET urlString:_requestStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dic = dict[@"data"];
        NSArray *array = dic[@"items"];
        for (NSDictionary *dic in array)
        {
            ListModel *model = [[ListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.listArray addObject:model];
        }
        [_listCollectionView reloadData];
        [_listCollectionView.footer endRefreshing];
        
    } error:^(NSError *error) {
        
    }];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableViewArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OtherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableView" forIndexPath:indexPath];
    cell.configure = self.tableViewArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyDetailsViewController *strategyVC = [[StrategyDetailsViewController alloc]init];
    strategyVC.contentId = ((OtherTableViewModel *)self.tableViewArray[indexPath.row]).Myid;
    strategyVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:strategyVC animated:YES];
    //strategyVC.hidesBottomBarWhenPushed = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
